package com.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class SessionUtil {
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
	private static StandardServiceRegistry registry = null;
	private static SessionFactory sessionFactory = null;
	
	static{
		registry = new StandardServiceRegistryBuilder().configure("com/config/hibernate.cfg.xml").build();
		sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
	}
	
	public static Session getSession(){
		Session session = threadLocal.get();
		if (session == null || !session.isOpen()) {
			session = (sessionFactory != null)?sessionFactory.openSession():null;
			threadLocal.set(session);
		}
		return session;
	}
	
	public static void closeSession() {
		Session session = threadLocal.get();
		threadLocal.set(null);
		if (session != null) {
			session.close();
		}
	}
}
